#include "../common/dispatch.hpp"
#include <thread>

void onRpcRequest(const rpc::BaseConnection::ptr conn, rpc::RpcRequest::ptr& msg)
{
    std::string str = msg->serialize();
    Json::Value val = msg->params();
    std::string method = msg->method();
    std::string id = msg->id();
    rpc::Mtype mtype = msg->mtype();
    std::cout << str << std::endl;

    rpc::RpcResponse::ptr rpc_rsp = rpc::MessageFactory::create<rpc::RpcResponse>();
    rpc_rsp->setid(id);
    rpc_rsp->setmtype(rpc::Mtype::RSP_RPC);
    rpc_rsp->setRcode(rpc::Rcode::RCODE_OK);
    rpc_rsp->setResult("33");
    conn->send(rpc_rsp);
}

void onTopicRequest(const rpc::BaseConnection::ptr conn, rpc::TopicRequest::ptr& msg)
{
    std::string str = msg->serialize();
    rpc::TopicOptype type = msg->optype();
    std::string key = msg->topicKey();
    std::string id = msg->id();
    rpc::Mtype mtype = msg->mtype();
    std::string message = msg->topicMsg();
    std::cout << str << std::endl;

    rpc::TopicResponse::ptr topic_rsp = rpc::MessageFactory::create<rpc::TopicResponse>();
    topic_rsp->setid(id);
    topic_rsp->setmtype(rpc::Mtype::RSP_TOPIC);
    topic_rsp->setRcode(rpc::Rcode::RCODE_OK);
    conn->send(topic_rsp);
}

int main()
{
    auto dispatcher = std::make_shared<rpc::Dispatcher>();
    dispatcher->registerHandler<rpc::RpcRequest>(rpc::Mtype::REQ_RPC,onRpcRequest);
    dispatcher->registerHandler<rpc::TopicRequest>(rpc::Mtype::REQ_TOPIC,onTopicRequest);
    
    auto server = rpc::ServerFactory::create(9090);
    auto msg_cb = std::bind(&rpc::Dispatcher::onMessage,dispatcher.get(),std::placeholders::_1,std::placeholders::_2);
    server->setMessageCallback(msg_cb);
    
    server->start();

    return 0;   
}
